<?php
require_once 'Paging.class.php';
	class  SqlHelper{
		public $conn;
		public $dbname = "emp";
		public $username = "root";
		public $password = "root";
		public $host ="localhost";
		
		public function __construct(){
			
			$this->conn = mysql_connect($this->host,$this->username,$this->password);
			if(!$this->conn){
				die("连接不成功".mysql_errno());
			}
			mysql_select_db($this->dbname,$this->conn);
		}
		//执行dql语句
		public function execute_sql($sql){
			$result = mysql_query($sql,$this->conn) or die(mysql_error());
			return $result;
		}
		
		//执行dql语句,但是返回的是一个数组
		public function execute_sql2($sql){
			$arr = array();
			$result = mysql_query($sql,$this->conn) or die(mysql_error());
			
			$i=0;
			while($row = mysql_fetch_assoc($result)){
				$arr[$i++]=$row;
			}
			//这里就可以马上把$res关闭
			mysql_free_result($result);
			return $arr;
		}
		
		//考虑分页的查询
		public function execute_sql_page($sql1,$sql2,$paging){
			$arr = array();
			$result = mysql_query($sql1,$this->conn) or die(mysql_error());
				
			while($row = mysql_fetch_assoc($result)){
				$arr[]=$row;
			}
			//这里就可以马上把$res关闭
			mysql_free_result($result);
			
			$paging->res_array = $arr;
			
			$result2 = mysql_query($sql2,$this->conn) or die(mysql_error());
			
			if ($row = mysql_fetch_row($result2 )) {
				$paging->pageCount =  ceil ( $row [0] / $paging->pageSize);
				$paging->rowCount = $row[0];
			}
			
			$navigation ="";
			// 上一页和下一页
			if ($paging->pageNow > 1) {
				$pagePre = $paging->pageNow - 1;
				$navigation="<a href='empList.php?pageNow=$pagePre'>上一页</a> &nbsp;";
			}
			if ($paging->pageNow < $paging->pageCount) {
				$pageNext = $paging->pageNow + 1;
				$navigation.="<a href='empList.php?pageNow=$pageNext'>下一页</a> &nbsp;";
			}
			
			// 当前页和总共页
			$navigation.="当前是{$paging->pageNow}页/共{$paging->pageCount}页<br>";
			$paging->navigation =$navigation;
		}
		//执行dml语句
		public function execute_dml($sql){
			$b = mysql_query($sql,$this->conn);
			if(!$b){
				return 0;
			}else{
				if(mysql_affected_rows($this->conn)>0){
					return 1;//表示执行Ok
				}else{
					return 2;//表示没有行受到影响
				}
			}
		}
		//关闭连接的方法
		public function close_connect(){
			if(!empty($this->conn)){
				mysql_close($this->conn);
			}
		}
	}
?>